<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 视图 -->
    <el-card class="box-card">
      <el-row :gutter="20" class="margin-b20">
        <el-col :span="20">
          <el-button type="primary" @click="userDialog=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <template>
            <el-table
              :data="userlist.filter(data => !search || data.username.toLowerCase().includes(search.toLowerCase()))"
              style="width: 100%"
            >
              <el-table-column label="注册日期" prop="reg_time"></el-table-column>
              <el-table-column label="用户名" prop="username"></el-table-column>
              <el-table-column label="性别" prop="sex"></el-table-column>
              <el-table-column label="手机号" prop="phone"></el-table-column>
              <el-table-column label="邮箱" prop="email"></el-table-column>
              <el-table-column align="right">
                <template slot="header" slot-scope="scope">
                  <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
                </template>
                <template slot-scope="scope">
                  <el-button size="mini" @click="editDialog(scope.$index, scope.row)">编辑</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="userDelete(scope.$index, scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
             <!-- 分页组件 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pagenum"
              :page-size="queryInfo.pagesize"
              layout="total, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </template>
         
        </el-col>

      </el-row>
      
    </el-card>

    <!-- 添加/编辑用户弹窗视图 -->
    <el-dialog title="添加用户" :visible.sync="userDialog" width="20%">
      <el-form :model="form" :rules="userFormRules" ref="form">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input type="text" maxlength="11" v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别"> 
          <el-radio label="0" v-model="form.sex" name="sex">男</el-radio>
          <el-radio label="1" v-model="form.sex" name="sex">女</el-radio>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="个人简介">
          <el-input
            type="textarea"
            placeholder="请输入个人简介"
            v-model="form.desc"
            maxlength="200"
            show-word-limit
          >
          </el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialog = false">取 消</el-button>
        <el-button type="primary" @click="userAdd()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户弹窗视图 -->
    <!-- <el-dialog title="编辑用户" :visible.sync="userEditDialog" width="20%">
      <el-form :model="editform" :rules="userFormRules" ref="editform">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="editform.username" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialog = false">取 消</el-button>
        <el-button type="primary" @click="userEdit()">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>
<script>
import { formatDatetime } from '../../utils/common'
export default {
  data() {
    return {
      // 分页配置
      queryInfo: {
          query: '',
          pagenum: 1,  // 当前第几页
          pagesize: 3  // 当前的页面显示多少条数据
      },
    // 用户总人数  
      total:0 ,
      //用户列表数据
      userData: [],
      userlist: [],
      search: "",  
      // 弹窗开启状态
      userDialog: false,
      // 用户数据
      form: {
        
        username: "",
        password: "",
        phone: "",
        sex: "0", 
        desc: "",
        email: "",
      },
      formLabelWidth: "70px",
      // 输入框校验规则
      userFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 11, max: 11, message: "请输入手机号", trigger: "blur" }
        ]
      }
      
    };
  },
  created() {
    this.userList();
  },
  computed: {     
  },
  methods: {
    // 请求用户列表
    async userList() {
      const that = this;
      const { data: res} = await that.$http.get("admin/user/list")
        if (res.code !== 200) {
            return that.$message.error('获取用户信息失败')
        }
        that.userData = res.data;
        that.total = res.data.length;
        let arr = []
        res.data.map((item,index)=>{
          if(index < that.queryInfo.pagesize ){
            item.reg_time = formatDatetime(item.reg_time);
            arr.push(item)
          }
        })
        that.userlist = arr
    },

    // 添加用户、编辑用户
    async userAdd() {
      const that = this;
      // console.log(that.form)
      // 请求添加、编辑用户接口
      const { data:res } = !that.form._id ? await that.$http.post("admin/user/userAdd", this.form) : await that.$http.post("admin/user/userEdit", this.form);
      if (res.code !== 200) {
        return that.$message({
          message: res.msg,
          type: "error"
        });
      }
      that.$message({
        message: res.msg,
        type: "success"
      });
      that.userList();
      that.queryInfo.pagenum = 1
      that.userDialog = false;
    },
    /**
     * 编辑用户信息
     */
    async userEdit() {
      const that = this;
      
    },
    // 编辑弹窗
    editDialog(index, row) {
      this.form = row;
      this.userDialog = true;
      this.userDialogTitle = this.form._id ? '编辑用户' : '添加用户'
    },
    /**
     * 删除用户信息
     */
    userDelete (index, row) {
      const that = this;
      that.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          that.$http.post("admin/user/userDelete", { id: row._id }).then((res) =>{
            if(res.data.code !== 200){
              return that.$message({
                type: "error",
                message: "删除失败"
              });
            } 
            that.$message({
              type: "success",
              message: "删除成功!"
            });
            that.userList();
          })
        })
        .catch(() => {
          that.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        let arr = [];
        this.userData.map(function (value,index){
          if(index < newSize){
            arr.push(value)
          }
        })
        this.userlist = arr;
    },
    handleCurrentChange(newPage) {
      const that = this;
        that.queryInfo.pagenum = newPage;
        let pagesize = that.queryInfo.pagesize;
        let arr = [];
        that.userlist = arr;
        that.userData.map(function (value,index){
          if(index < newPage * pagesize){
            if(index >= (newPage-1) * pagesize ){
              arr.push(value)
            }
          }
        })
        that.userlist = arr;
    }
  }
};
</script>
<style>
.box-card {
  background-color: #fff;
}
.el-row {
  margin-bottom: 20px;
}
</style>
